import fs from "fs"
import path from "path"
import http from "http"
import https from "https"

import { fileURLToPath } from 'url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export const  writeFile = async (pathName,data)=>{
       await fs.writeFileSync(pathName, data, 'utf8', (err,dataStr) => {
        if (err) throw err;
        return dataStr
    });
}
export const saveFile = (buffer,name,type)=>{
    const pathName = path.join(__dirname, `../files/${name}`)
    const res= type ? writeFile(pathName,buffer,type) : writeFile(pathName,buffer)
    return pathName
}
export const getUrl = (name)=>{
    const pathName = path.join(__dirname, `../files/${name}`)
    return pathName
}
export const removeFile = (name)=>{
    fs.unlink(name,(e,str)=>{
        return '1'
    })
}

export const downloadUrl = (url,type)=>{
    type=type || 'binary'
    const api = url.indexOf('https')>-1 ? https : http
        return  new Promise((resolve,roject)=>{
            api.get(url,async (res)=>{
                let data = '';
                res.setEncoding(type)
                res.on('data', (chunk) => {
                    data += chunk;
                  });
                res.on('end',async()=>{
                    const buffer = Buffer.from(data,type || 'binary');
                    // const fileNameType = await fileType(buffer)
                  let  fileNameType = res.headers['content-type']
                  if(fileNameType)  fileNameType=   fileNameType.split('/').pop().split(';')[0] 
             
                    console.log(fileNameType)
                    // console.log(buffer)
                    const name= saveFile(buffer,new Date().getTime()+'.'+(fileNameType||'png'))
                    resolve({buffer,name,type})
                })
    
            })
        })
}